import os
import uvicorn

from fastapi import FastAPI
from langserve import add_routes

from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

os.environ["LANGSMITH_TRACING_V2"] = "true"
os.environ["LANGSMITH_API_KEY"] = "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"
os.environ["OPENAI_BASE_URL"] = "https://api.chatanywhere.tech/v1"
os.environ["OPENAI_API_KEY"] = "sk-pbXvhNj37SZ5SUBzC1Kx4LeXrsnT9EJNDL6mT2Lj2IbgohKa"

prompt_template = ChatPromptTemplate.from_messages([
    ("system", "{role}"),
    ("user", "{text}")
])
model = ChatOpenAI(model="gpt-4o-mini")
parse = StrOutputParser()
chain = prompt_template | model | parse

app = FastAPI(title="Langchain服务", version="1.0.0", description="使用Langchain调用chatgpt的服务")

add_routes(
    app,
    chain,
    path="/chain"
)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0")
